/**
 * @swagger
 * /api/high-goods/unit-analysis:
 *   get:
 *     tags:
 *       - 高价值品统计
 *     summary: 获取单位高价值品分析数据
 *     description: 按单位统计高价值品数量和金额的分布与排名，支持时间筛选
 *     parameters:
 *       - in: query
 *         name: startTime
 *         schema:
 *           type: string
 *           format: date
 *         description: 开始时间 (YYYY-MM-DD)
 *         example: "2023-01-01"
 *       - in: query
 *         name: endTime
 *         schema:
 *           type: string
 *           format: date
 *         description: 结束时间 (YYYY-MM-DD)
 *         example: "2023-12-31"
 *     responses:
 *       200:
 *         description: 成功获取单位分析数据
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                   description: 响应状态码
 *                 message:
 *                   type: string
 *                   example: "单位分析获取成功"
 *                   description: 响应消息
 *                 data:
 *                   type: object
 *                   properties:
 *                     quantityRanking:
 *                       type: object
 *                       properties:
 *                         description:
 *                           type: string
 *                           example: "单位高价值品数量排行榜（Top 20）"
 *                         data:
 *                           type: array
 *                           items:
 *                             type: object
 *                             properties:
 *                               rank:
 *                                 type: integer
 *                                 description: 排名
 *                               unitName:
 *                                 type: string
 *                                 description: 单位名称
 *                               totalQuantity:
 *                                 type: integer
 *                                 description: 总数量
 *                               totalAmount:
 *                                 type: number
 *                                 description: 总金额
 *                               recordCount:
 *                                 type: integer
 *                                 description: 记录数
 *                               avgQuantity:
 *                                 type: number
 *                                 description: 平均数量
 *                               avgAmount:
 *                                 type: number
 *                                 description: 平均金额
 *                     amountRanking:
 *                       type: object
 *                       properties:
 *                         description:
 *                           type: string
 *                           example: "单位高价值品金额排行榜（Top 20）"
 *                         data:
 *                           type: array
 *                           items:
 *                             type: object
 *                             properties:
 *                               rank:
 *                                 type: integer
 *                                 description: 排名
 *                               unitName:
 *                                 type: string
 *                                 description: 单位名称
 *                               totalAmount:
 *                                 type: number
 *                                 description: 总金额
 *                               totalQuantity:
 *                                 type: integer
 *                                 description: 总数量
 *       500:
 *         description: 服务器内部错误
 */
const { query } = require('../../../lib/db');
const { success, error: createError, handleResponse } = require('../../../lib/response');
const { withCors } = require('../../../lib/cors');

/**
 * 单位高价值品分析接口处理函数
 * @param {Object} req - 请求对象
 * @param {Object} req.query - 查询参数
 * @param {string} [req.query.startTime] - 开始时间
 * @param {string} [req.query.endTime] - 结束时间
 * @param {Object} res - 响应对象
 * @returns {Promise<Object>} 返回单位分析数据
 */
async function handler(req, res) {

  try {
    // 获取时间筛选参数
    const { startTime, endTime } = req.query;
    
    // 构建时间筛选条件
    let timeCondition = '';
    if (startTime || endTime) {
      const conditions = [];
      if (startTime) conditions.push(`TJSJ >= '${startTime}'`);
      if (endTime) conditions.push(`TJSJ <= '${endTime}'`);
      timeCondition = ` AND ${conditions.join(' AND ')}`;
    }
    // 单位数量排行 Top 20
    const unitQuantityQuery = `
      SELECT 
        DWMC as unitName,
        SUM(COALESCE(GJZSL, 0)) as totalQuantity,
        SUM(COALESCE(GJZJE, 0)) as totalAmount,
        COUNT(*) as recordCount,
        AVG(COALESCE(GJZSL, 0)) as avgQuantity,
        AVG(COALESCE(GJZJE, 0)) as avgAmount
      FROM wd_zcgk_gjzzcdwfb
      WHERE DWMC IS NOT NULL AND DWMC != ''${timeCondition}
      GROUP BY DWMC
      ORDER BY totalQuantity DESC
      LIMIT 20
    `;

    const unitQuantityResult = await query(unitQuantityQuery);

    // 单位金额排行 Top 20
    const unitAmountQuery = `
      SELECT 
        DWMC as unitName,
        SUM(COALESCE(GJZJE, 0)) as totalAmount,
        SUM(COALESCE(GJZSL, 0)) as totalQuantity,
        COUNT(*) as recordCount,
        AVG(COALESCE(GJZJE, 0)) as avgAmount,
        AVG(COALESCE(GJZSL, 0)) as avgQuantity
      FROM wd_zcgk_gjzzcdwfb
      WHERE DWMC IS NOT NULL AND DWMC != ''${timeCondition}
      GROUP BY DWMC
      ORDER BY totalAmount DESC
      LIMIT 20
    `;

    const unitAmountResult = await query(unitAmountQuery);

    const responseData = {
      quantityRanking: {
        description: "单位高价值品数量排行榜（Top 20）",
        data: unitQuantityResult.map((item, index) => ({
          rank: index + 1,
          unitName: item.unitName,
          totalQuantity: parseInt(item.totalQuantity),
          totalAmount: parseFloat(item.totalAmount).toFixed(2),
          recordCount: parseInt(item.recordCount),
          avgQuantity: parseFloat(item.avgQuantity).toFixed(2),
          avgAmount: parseFloat(item.avgAmount).toFixed(2)
        }))
      },
      amountRanking: {
        description: "单位高价值品金额排行榜（Top 20）",
        data: unitAmountResult.map((item, index) => ({
          rank: index + 1,
          unitName: item.unitName,
          totalAmount: parseFloat(item.totalAmount).toFixed(2),
          totalQuantity: parseInt(item.totalQuantity),
          recordCount: parseInt(item.recordCount),
          avgAmount: parseFloat(item.avgAmount).toFixed(2),
          avgQuantity: parseFloat(item.avgQuantity).toFixed(2)
        }))
      }
    };

    return handleResponse(res, success(responseData, "单位分析获取成功"));
    
  } catch (err) {
    console.error('High goods unit analysis error:', err);
    return handleResponse(res, createError("获取单位分析失败", 500));
  }
}

export default withCors(handler, ['GET']);